<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { ElSwitch } from 'element-plus'

import { BaseButton } from '@/components/Button'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
import { Table, TableColumn } from '@/components/Table'

import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'

import { useDictStore } from '@/store/Admin/dict'

import { selectDictLabel, DictDetail } from '@/utils/dict'

import { getMenuTreeApi, saveMenuInfoApi } from '@/api/Admin/auth/menu'
import Write from './components/Write.vue'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getMenuTreeApi({})
    return {
      list: res.data || [],
      total: res.count || 0
    }
  }
})

const { dataList, loading } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'title',
    label: t('admin.menu.title'),
    slots: {
      default: (data: any) => {
        const title = data.row.title
        return <>{title}</>
      }
    }
  },
  {
    field: 'icon',
    label: t('admin.menu.icon'),
    slots: {
      default: (data: any) => {
        const icon = data.row.icon
        if (icon) {
          return (
            <>
              <Icon icon={icon} />
            </>
          )
        } else {
          return null
        }
      }
    }
  },
  {
    field: 'menu_type',
    label: t('admin.menu.type'),
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <span>{selectDictLabel(menuTypeOptions.value, row.menu_type)}</span>
          </>
        )
      }
    }
  },
  {
    field: 'path',
    label: t('admin.menu.path')
  },
  {
    field: 'component',
    label: t('admin.menu.component'),
    slots: {
      default: (data: any) => {
        const component = data.row.component
        return <>{component === '#' ? '顶级目录' : component === '##' ? '子目录' : component}</>
      }
    }
  },
  {
    field: 'perms',
    label: t('admin.menu.perms')
  },
  {
    field: 'noCache',
    label: t('admin.menu.cache'),
    show: true,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <ElSwitch modelValue={!row.noCache} disabled />
          </>
        )
      }
    }
  },
  {
    field: 'hidden',
    label: t('common.status.hidden'),
    show: true,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <ElSwitch modelValue={row.hidden} disabled />
          </>
        )
      }
    }
  },
  {
    field: 'disabled',
    label: t('common.status.disabled'),
    width: '120px',
    show: true,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <ElSwitch modelValue={row.disabled} disabled />
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('common.action.title'),
    width: 240,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" link size="small" onClick={() => action(row, 'edit')}>
              {t('common.action.edit')}
            </BaseButton>
            <BaseButton type="success" link size="small" onClick={() => action(row, 'detail')}>
              {t('common.action.detail')}
            </BaseButton>
            <BaseButton type="danger" link size="small">
              {t('common.action.delete')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const menuTypeOptions = ref<DictDetail[]>([])

const getOptions = async () => {
  const dictStore = useDictStore()
  const dictOptions = await dictStore.getDictObj(['sys_dict_menu_type'])
  menuTypeOptions.value = dictOptions.sys_dict_menu_type
}

getOptions()

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.dialog.edit' : 'common.dialog.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const addAction = () => {
  dialogTitle.value = t('common.dialog.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res = await saveMenuInfoApi(formData)
      if (res) {
        dialogVisible.value = false
        getList()
      }
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <BaseButton type="primary" @click="addAction">{{ t('component.button.add') }}</BaseButton>
    </div>
    <Table
      showAction
      :columns="tableColumns"
      node-key="id"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      @refresh="getList"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />

    <Write v-if="actionType === 'detail'" ref="writeRef" :current-row="currentRow" disabled />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('component.button.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('component.button.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
